package us.nchu.tomtiger.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import us.nchu.tomtiger.utils.EncryptUtil;
import us.nchu.tomtiger.utils.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by XiongXuan on 2018/1/11.
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {
    // spring中不支持直接进行静态变量值的注入，这里利用spring的set注入方法，通过非静态的setter方法注入静态变量
    private static String ADMIN_URL;
    @Value("${app.config.admin_url}")
    public void setAdminUrl(String url) {
        ADMIN_URL = url;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (httpServletRequest.getRequestURI().equals(ADMIN_URL)) {
            // 如果用户访问的是管理员的登录界面，则放行
            return true;
        }
        // 判断用户是否已经登录，如果已经登录，则放行，没有登录则拒绝
        if (httpServletRequest.getSession().getAttribute("adminId") == null) {
            httpServletResponse.sendRedirect(ADMIN_URL);
        }
        return httpServletRequest.getSession().getAttribute("adminId") != null;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
